<template>
  <div class="box">
    <div
      class="left"
      :style="{ width: statementData.payStatus ? '100%' : '60%' }"
    >
      <el-descriptions :column="statementData.payStatus ? 3 : 2">
        <el-descriptions-item label="客户姓名">{{
          statementData.customerName
        }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{
          statementData.customerPhone
        }}</el-descriptions-item>
        <el-descriptions-item label="车牌号码">{{
          statementData.licensePlate
        }}</el-descriptions-item>
        <el-descriptions-item label="汽车类型">
          <el-tag size="small">{{ statementData.carType }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="服务类型">
          <dict-tag
            :options="dict.type.cmi_service_type"
            :value="statementData.serviceType"
          />
        </el-descriptions-item>
        <el-descriptions-item label="到店时间">{{
          statementData.arrivalTime
        }}</el-descriptions-item>
        <el-descriptions-item label="总消费金额">{{
          statementData.payStatus
            ? statementData.totalAmount.toFixed(2)
            : totalAmount.toFixed(2)
        }}</el-descriptions-item>
        <el-descriptions-item label="实付价格">{{
          statementData.payStatus
            ? statementData.discountAmount.toFixed(2)
            : discountAmount.toFixed(2)
        }}</el-descriptions-item>
        <el-descriptions-item label="优惠价格">
          <el-badge
            :value="waringMsg"
            class="item"
            v-if="!statementData.payStatus"
          >
            <el-input
              size="mini"
              style="width: 200px"
              placeholder="请输入优惠价格"
              maxlength="8"
              prop="money"
              v-model="money"
            >
              <i slot="prefix" class="el-input__icon">&yen;</i>
            </el-input>
          </el-badge>
          <template v-else>{{ preferentialPrice.toFixed(2) }}</template>
        </el-descriptions-item>
        <el-descriptions-item v-if="statementData.payStatus" label="收款时间">{{
           statementData.payTime
        }}</el-descriptions-item>
        <el-descriptions-item v-if="statementData.payStatus" label="收款人">{{
           statementData.payeeId
        }}</el-descriptions-item>
      </el-descriptions>
      <div class="box_bottom" :style="{ height: statementData.payStatus ? '90%' : '65%' }">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5" v-if="!statementData.payStatus">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleSave"
              v-hasPermi="['workflow:statementItem:save']"
              >保存</el-button
            >
          </el-col>
          <el-col :span="1.5" v-if="!statementData.payStatus">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handlePay"
              v-hasPermi="['workflow:statementItem:pay']"
              >确认支付</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <span class="totalStyle">共 {{ statementItemTotal }} 条记录</span>
          </el-col>
        </el-row>
        <el-table :data="statementItem" height="80%">
          <el-table-column align="center" prop="itemName" label="服务项名称">
          </el-table-column>
          <el-table-column
            align="center"
            prop="itemPrice"
            label="服务项价格"
            :formatter="formatOriginalPrice"
          >
          </el-table-column>
          <el-table-column align="center" prop="itemQuantity" label="购买数量">
          </el-table-column>
          <el-table-column
            v-if="!statementData.payStatus"
            width="150px"
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="danger"
                circle
                icon="el-icon-minus"
                @click="handleMinus(scope.$index)"
                v-hasPermi="['workflow:statement:edit']"
              ></el-button>
              <el-button
                size="small"
                type="primary"
                circle
                icon="el-icon-plus"
                @click="handlePlus(scope.$index)"
                v-hasPermi="['workflow:statement:edit']"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="right" v-if="!statementData.payStatus">
      <div class="r_top">
        <el-form
          :model="serviceItemQueryParams"
          ref="queryForm"
          inline
          label-width="68px"
        >
          <el-form-item label="服务名称" prop="name">
            <el-input
              v-model="serviceItemQueryParams.name"
              style="width: 215px"
              placeholder="请输入服务名称"
              size="small"
            />
          </el-form-item>
          <el-form-item label="是否套餐" prop="carPackage">
            <el-select
              v-model="serviceItemQueryParams.carPackage"
              placeholder="请选择是否套餐"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in dict.type.si_car_package"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="服务类型" prop="serviceCatalog">
            <el-select
              v-model="serviceItemQueryParams.serviceCatalog"
              placeholder="请选择服务类型"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in dict.type.cmi_service_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="r_bottom">
        <el-row :gutter="10" class="mb8">
          <pagination
            v-show="serviceItemListTotal > 0"
            :total="serviceItemListTotal"
            :page.sync="serviceItemQueryParams.pageNum"
            :limit.sync="serviceItemQueryParams.pageSize"
            @pagination="queryByCondition"
            layout="total,sizes,prev, next, jumper"
          />
        </el-row>
        <el-table :data="serviceItemList" v-loading="loading" height="80%">
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            prop="name"
            label="服务名称"
          >
          </el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            prop="originalPrice"
            label="服务价格"
            :formatter="formatOriginalPrice"
          >
          </el-table-column>
          <el-table-column
            align="center"
            :show-overflow-tooltip="true"
            prop="info"
            label="备注信息"
          >
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="primary"
                circle
                icon="el-icon-plus"
                @click="handleAddStatementItem(scope.row)"
                v-hasPermi="['workflow:statement:edit']"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getStatementItemByAppointmentInfoId,
  getStatementItemByStatementId,
  listServiceItem,
  saveStatementItem,
  payStatementItem,
} from "@/api/workflow/statementItem";

export default {
  name: "Item",
  dicts: ["cmi_service_type", "si_car_package"],
  data() {
    return {
      loading: false,
      //结算单用户信息
      statementData: {},
      //优惠价格
      money: 0,
      //优惠价格警告信息
      waringMsg: "",
      //所有的结算单服务明细,表格展示
      statementItem: [],
      //结算单服务明细总数量
      statementItemTotal: 0,
      //记录结算单服务明细变动数据,包括已保存和未保存
      statementItemTemp: [],
      //记录删除的id，并且数据库中已存在的
      statementItemTempDel: [],
      //记录数据库中的数据
      statementItemDB: [],
      //所有服务项
      serviceItemList: [],
      //所有服务项总数量
      serviceItemListTotal: 0,
      // 服务明细查询参数
      // queryParams: {
      //   pageNum: 1,
      //   pageSize: 10,
      //   appointmentInfoId: 0,
      // },
      // 所有服务项查询参数
      serviceItemQueryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        carPackage: null,
        serviceCatalog: null,
        saleStatus: 1,
      },
    };
  },
  //钩子函数
  created() {
    this.getStatementItem();
  },
  //监听
  watch: {
    //当顶部导航没有关闭时,组件不会重载，通过监听的方式，
    //解决方案：当路由传参的id发生变化时，就调用
    "$route.query.statementId": {
      handler(newVal, oldVal) {
        if (newVal != undefined) {
          this.getStatementItem();
        }
      },
    },
    "$route.query.appointmentInfoId": {
      handler(newVal, oldVal) {
        if (newVal != undefined) {
          this.getStatementItem();
        }
      },
    },
  },
  computed: {
    //计算结算单明细的总消费金额
    totalAmount() {
      return this.statementItem.reduce((sum, cur) => {
        return (sum += cur.itemPrice * cur.itemQuantity);
      }, 0);
    },
    //计算结算单明细的实付价格
    discountAmount() {
      return this.totalAmount - this.money < 0
        ? 0
        : this.totalAmount - this.money;
    },
    //计算优惠价格
    preferentialPrice() {
      return this.statementData.payStatus == 1
        ? this.statementData.totalAmount - this.statementData.discountAmount
        : this.totalAmount - this.discountAmount;
    },
  },
  methods: {
    //格式化表格价格的值
    formatOriginalPrice(row, column) {
      const originalPrice = row[column.property];
      // 在这里进行你的过滤或格式化操作
      // 返回处理后的结果
      return originalPrice.toFixed(2); // 简单示例，保留两位小数
    },
    //查询结算单明细
    async getStatementItem() {
      let appointmentInfoId = this.$route.query.appointmentInfoId;
      let statementId = this.$route.query.statementId;
      let appintmentInfoResp = null;
      //查看结算单明细
      if (appointmentInfoId) {
        appintmentInfoResp = await getStatementItemByAppointmentInfoId(
          appointmentInfoId
        );
      } else if (statementId) {
        appintmentInfoResp = await getStatementItemByStatementId(statementId);
      }

      if (appintmentInfoResp.code === 200) {
        let data = appintmentInfoResp.data;
        //结算单用户信息
        this.statementData = data.statementObj;
        //结算单服务明细
        this.statementItem = data.statementItem;
        //记录数据库中结算单服务明细
        this.statementItemDB = JSON.parse(JSON.stringify(data.statementItem)); //深拷贝,而不是浅拷贝，浅拷贝是地址指向
        //结算单明细服务总项
        this.statementItemTotal = data.statementItem.length;
        this.loading = false;
      }

      //当状态为：消费中，则查询所有服务项
      if (
        appintmentInfoResp.data &&
        appintmentInfoResp.data.statementObj.payStatus == 0
      ) {
        this.queryByCondition();
      }
    },
    //添加服务项
    handleAddStatementItem(scope) {
      //先判断，如果在添加的服务项中有存在的，则不添加
      let index = this.statementItem.findIndex(
        (item) => item.itemName === scope.name
      );
      if (index >= 0) {
        this.$message({
          type: "warning",
          message: "服务项已存在!",
        });
        return;
      }
      let addServiceItemObj = {
        statementId: this.statementData.id,
        itemId: scope.id,
        itemName: scope.name,
        itemPrice: scope.originalPrice,
        itemQuantity: 1,
        carPackage: scope.carPackage, //用于判断是否是套餐，不作为表单提交
      };
      //巧合：当同个对象添加到两个不同的列表时，一个列表的对象数据变动，而另外一个列表中同个对象的数据也变
      //原理：同个对象，内存地址也相同。

      //保存所用，用于展示列表
      this.statementItem.unshift(addServiceItemObj);

      //记录变动的数据
      this.statementItemTemp.unshift(addServiceItemObj);

      //结算单明细服务总项
      this.statementItemTotal = this.statementItem.length;
    },
    //服务项数量 -1
    handleMinus(index) {
      //改变展示列表的数量
      this.statementItem[index].itemQuantity--;

      //记录变动的数据，如果是数据库中存在的，就先添加后记录
      let updateIndex = this.statementItemTemp.findIndex(
        (item) => item.itemName == this.statementItem[index].itemName
      );
      //如果记录的数据不存在，就先添加记录，再记录变化的数据
      if (updateIndex == -1) {
        this.statementItemTemp.unshift(this.statementItem[index]);
      }

      if (this.statementItem[index].itemQuantity == 0) {
        //先记录变动的数据
        this.statementItemTemp.splice(
          this.statementItemTemp.findIndex(
            (item) => item.itemName == this.statementItem[index].itemName
          ),
          1
        );
        //删除前，先判断该服务项是在数据库已经保存还是未保存的。如果是已保存，则要记录起来后到数据库中删除
        let delIndex = this.statementItemDB.findIndex(
          (item) => item.itemName == this.statementItem[index].itemName
        );
        if (delIndex >= 0) {
          this.statementItemTempDel.push(this.statementItemDB[delIndex].id);
        }
        //当数量为0，则再删除
        this.statementItem.splice(index, 1);
      }
      //结算单明细服务总项
      this.statementItemTotal = this.statementItem.length;
    },
    //服务项数量 +1
    handlePlus(index) {
      //如果是套餐，则数量只能为1，不能再加了
      if (this.statementItem[index].carPackage == 1) {
        this.$message({ type: "warning", message: "套餐购买数量最多: 1" });
        return;
      }
      //改变展示列表的数量
      this.statementItem[index].itemQuantity++;
      //结算单明细服务总项
      this.statementItemTotal = this.statementItem.length;

      //记录变动的数据，如果是数据库中存在的，就先添加后记录
      let updateIndex = this.statementItemTemp.findIndex(
        (item) => item.itemName == this.statementItem[index].itemName
      );
      //如果记录的数据不存在，就先添加记录，再记录变化的数据
      if (updateIndex == -1) {
        this.statementItemTemp.unshift(this.statementItem[index]);
      }
    },
    //处理服务项条件搜索
    async queryByCondition() {
      let serviceItemResp = await listServiceItem(this.serviceItemQueryParams);
      if (serviceItemResp.code === 200) {
        this.serviceItemList = serviceItemResp.rows;
        this.serviceItemListTotal = serviceItemResp.total;
      }
    },
    //服务项条件搜索按钮
    handleQuery() {
      this.queryByCondition();
    },

    //校验手机号码
    // validMoneyType() {
    //   let rex = /^\d{2,9}(\.\d{2})?$/;
    //   if (!rex.test(this.money)) {
    //     this.$refs["moneyInput"].focus();
    //     this.waringMsg = "只能输入数字";
    //   }
    // },

    //保存结算单明细确认框
    handleSave() {
      this.$confirm("确认是否保存结算单明细", "确认框", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.todoSave();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消保存",
          });
        });
    },
    //保存结算单明细
    todoSave() {
      //保存之前，先判断是否有变动，如果没有变动，则取消保存，防止表单重复提交
      if (
        this.statementItemTemp.length == 0 &&
        this.statementItemTempDel.length == 0
      ) {
        this.$message.error("不能重复保存!!!");
        return;
      }

      let data = {
        statementItemList: this.statementItemTemp, //记录结算单服务明细变动数据,包括已保存和未保存【通过有无id区分】
        delStatementItemIds: this.statementItemTempDel, //记录删除的id，并且数据库中已存在的
      };
      saveStatementItem(data).then((res) => {
        //保存成功后，清除记录
        this.statementItemTemp = [];
        this.statementItemTempDel = [];
        this.$message({
          type: "success",
          message: "保存成功",
        });
        this.getStatementItem();
      });
    },

    //确认支付
    handlePay() {
      this.$confirm("确认是否支付", "支付框", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.todoPay();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消支付",
          });
        });
    },
    todoPay() {
      //确认支付前，要先判断是否已经保存，只有保存了才可以确认支付
      console.log("statementItemTemp:", this.statementItemTemp);
      console.log("statementItemTempDel:", this.statementItemTempDel);
      if (
        this.statementItemTemp.length > 0 ||
        this.statementItemTempDel.length > 0
      ) {
        this.$message.error("先保存,才能支付!!!");
        return;
      }

      let formData = new FormData();
      formData.append("statementId", this.statementData.id);
      formData.append("preferentialPrice", this.money);

      payStatementItem(formData).then((res) => {
        this.$message({
          type: "success",
          message: "支付成功",
        });
        this.getStatementItem();
      });
    },
  },
};
</script>

<style>
.box {
  background-color: #f3f3f4;
  position: absolute;
  width: 100%;
  height: 100%;
  padding: 10px;
  display: flex;
  box-sizing: border-box;
}

.left {
  width: 60%;
  margin-right: 10px;
  display: flex;
  flex-direction: column;
}

.left .totalStyle {
  color: #606266;
  font-size: 13px;
  vertical-align: -webkit-baseline-middle;
}

.left .el-descriptions {
  margin-bottom: 10px;
  box-sizing: border-box;
  height: 35%;
}

.left .el-descriptions__body {
  box-shadow: 10px 10px 10px #ccc;
  border-radius: 10px;
  padding: 10px 20px 0;
  box-sizing: border-box;
}

.left .box_bottom {
  height: 65%;
  background-color: #fff;
  padding: 10px;
  box-shadow: 10px 10px 10px #ccc;
  border-radius: 10px;
  box-sizing: border-box;
}

.right {
  width: 40%;
}

.right .r_top {
  height: 35%;
  box-shadow: 10px 10px 10px #ccc;
  background-color: #fff;
  border-radius: 10px;
  padding: 10px 10px 0;
  margin-bottom: 10px;
  box-sizing: border-box;
}

.right .r_top .el-form .el-form-item {
  margin-bottom: 18px;
  box-sizing: border-box;
}

.right .pagination-container {
  margin: 0;
  padding: 0 !important;
}

.right .r_bottom {
  box-shadow: 10px 10px 10px #ccc;
  background-color: #fff;
  border-radius: 10px;
  padding: 10px 10px 0;
  box-sizing: border-box;
  height: 63%;
}
</style>